﻿using SuperiorCommon;
using SuperiorModel;
using SuperiorSqlTools;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace SuperiorShopDataAccess
{
    public class OrderDataAccess
    {
        public static DataSet Search(OrderCriteria criteria)
        {
            var sqlManager = new SqlManager();
            List<SqlParameter> parms = new List<SqlParameter>();
            var sb = sqlManager.CreateSb();

            if (criteria.AppType != 999)
            {
                sb.Append(" and o.AppType=@AppType ");
                parms.Add(new SqlParameter("@AppType", criteria.AppType));
            }
            if (criteria.ShopAppId != "unChecke")
            {
                sb.Append(" and o.ShopAppId=@ShopAppId ");
                parms.Add(new SqlParameter("@ShopAppId", criteria.ShopAppId.ToInt()));
            }
            if (criteria.ShopAdminId != 0)
            {
                sb.Append(" and o.ShopAdminId=@ShopAdminId ");
                parms.Add(new SqlParameter("@ShopAdminId", criteria.ShopAdminId));
            }
            if (!string.IsNullOrEmpty(criteria.OrderNo))
            {
                sb.Append(" and o.OrderNo=@OrderNo ");
                parms.Add(new SqlParameter("@OrderNo", criteria.OrderNo));
            }
            if (!string.IsNullOrEmpty(criteria.LoginName))
            {
                sb.Append(" and o.LoginName=@LoginName ");
                parms.Add(new SqlParameter("@LoginName", criteria.LoginName));
            }
            if (criteria.OrderStatus != 999)
            {
                sb.Append(" and o.OrderStatus=@OrderStatus ");
                parms.Add(new SqlParameter("@OrderStatus", criteria.OrderStatus));

            }
            if (!string.IsNullOrEmpty(criteria.BeginTime))
            {
                sb.Append(" and o.CreateTime>=@BeginTime ");
                parms.Add(new SqlParameter("@BeginTime", criteria.BeginTime));
            }
            if (!string.IsNullOrEmpty(criteria.EndTime))
            {
                sb.Append(" and o.CreateTime<=@EndTime ");
                parms.Add(new SqlParameter("@EndTime", criteria.EndTime));
            }
            var sql = string.Format("select top({0}) * from (select ROW_NUMBER() over(order by o.Id desc)as rownum,ISNULL(s.ShopName,'') as ShopName,u.NickName,o.Id,o.OrderNo,o.RealityAmount,o.PayOderNo,o.OrderStatus,o.CreateTime,o.PayTime,o.SendTime,o.FailReason,o.AppType,o.ServiceStatus,o.LoginName from C_Order o left join C_ShopApp s on o.ShopAppId=s.Id left join C_Users u on o.UserId=u.Id where {1} )tt where tt.rownum>{2};select count(*) as totalCount from C_Order o where {1} ", criteria.PagingResult.PageSize, sb.ToString(), criteria.PagingResult.PageSize * criteria.PagingResult.PageIndex);
            return sqlManager.ExecuteDataset(CommandType.Text, sql, parms.ToArray());
        }

        public static DataSet GetDetail(int orderid)
        {
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderid",orderid)
            };
            var sql = "select * from C_Order where Id=@orderid;select ProductName, BuyNum, SalePrice, ProppetyCombineName, SkuCode from C_OrderDetails where OrderId = @orderid";
            return sqlManager.ExecuteDataset(CommandType.Text, sql, parms);
        }

        public static void SendProduct(SendProductParms model)
        {
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderid",model.Id.ToInt()),
                new SqlParameter("@DeliveryName",model.DeliveryName),
                new SqlParameter("@DeliveryNo",model.DeliveryNo),
            };
            var sql = "update C_Order set OrderStatus = 1,SendTime=getdate(),SendStatus=1,DeliveryName=@DeliveryName,DeliveryNo=@DeliveryNo where Id=@orderid";
            sqlManager.ExecuteNonQuery(CommandType.Text, sql, parms);
        }

        public static void UpdateDelivery(SendProductParms model)
        {
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderid",model.Id.ToInt()),
                new SqlParameter("@DeliveryName",model.DeliveryName),
                new SqlParameter("@DeliveryNo",model.DeliveryNo),
            };
            var sql = "update C_Order set DeliveryName=@DeliveryName,DeliveryNo=@DeliveryNo where Id=@orderid";
            sqlManager.ExecuteNonQuery(CommandType.Text, sql, parms);
        }

        public static void FinishService(int orderid)
        {
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderid",orderid)
            };
            var sql = "update C_Order set ServiceStatus = 1,ServiceTime=getdate() where Id=@orderid";
            sqlManager.ExecuteNonQuery(CommandType.Text, sql, parms);
        }

        #region 接口
        public static DataSet Program_CreateOrder_Cart(Api_CreateOrderCriteria model, out int ret)
        {
            var sqlManager = new SqlManager();
            SqlParameter rtn_err = sqlManager.GetRtnParameter();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderno", ToolManager.CreateNo()),
                new SqlParameter("@userid",model.UserId.ToInt()),
                new SqlParameter("@spid", model.Spid.ToInt()),
                new SqlParameter("@said", model.Said.ToInt()),
                new SqlParameter("@consigneeId", model.ConsigneeId),
                new SqlParameter("@remark", model.Remarks.IsNull()),
                new SqlParameter("@couponId", model.CouponId),
                new SqlParameter("@shipAmount", model.ShipAmount),
                new SqlParameter("@totalAmount", model.ToalAmount),
                new SqlParameter("@apptype", model.AppType),
                new SqlParameter("@productAmount",model.ProductAmount),
                new SqlParameter("@couponAmount",model.CouponAmount),
                rtn_err

            };
            var ds = sqlManager.ExecuteDataset(CommandType.StoredProcedure, "[programe_create_order_cart]", parms);
            if (rtn_err.Value != null)
            {
                ret = int.Parse(rtn_err.Value.ToString());
                return ds;

            }
            ret = -1;
            return null;

        }

        public static int Program_WxNotice_Cart(string out_trade_no, int status, float total_fee, string transaction_id)
        {
            var sqlManager = new SqlManager();
            SqlParameter rtn_err = sqlManager.GetRtnParameter();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderno", out_trade_no),
                new SqlParameter("@totalFee", total_fee),
                new SqlParameter("@status",status),
                new SqlParameter("@transaction_id", transaction_id),
                rtn_err

            };
            sqlManager.ExecuteNonQuery(CommandType.StoredProcedure, "[program_wx_notice_cart]", parms);
            if (rtn_err.Value != null)
            {
                return int.Parse(rtn_err.Value.ToString());
            }
            return -1;
        }

        public static DataSet Api_GetDetail(int orderid)
        {
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderid",orderid)
            };
            var sql = "select ConsigneeName,ConsigneePhone,Address,RealityAmount,OrderNo,Remark,CreateTime,PayTime,CouponDelAmount,ShippingAmount,CouponName,Id,OrderAmount,DeliveryName,DeliveryNo,isnull((select top(1) Id from C_Comment with(nolock) where OrderId=@orderid order by Id),0)as CommentId  from C_Order where Id= @orderid;select ProductId, ProductName, ProppetyCombineName, BuyNum, SalePrice,(select ImagePath from C_ProductImg where ProductId = od.ProductId and IsDefault = 1 and IsDel = 0) as ImagePath from C_OrderDetails od where OrderId = @orderid";
            return sqlManager.ExecuteDataset(CommandType.Text, sql, parms); 
        }

        public static DataSet Api_GetOrderList(Api_OrderListCriteria criteria)
        {
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@spid",criteria.Spid.ToInt()),
                new SqlParameter("@userid",criteria.UserId.ToInt()),
                new SqlParameter("@offset",criteria.OffSet),
                new SqlParameter("@size",criteria.Size),
                new SqlParameter("@orderstatus",criteria.OrderStatus)
            };
            return sqlManager.ExecuteDataset(CommandType.StoredProcedure, "getorderlist_program", parms);
        }
        public static DataSet Api_GetOrderStatus(int orderId)
        {
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderId",orderId)
            };
            var sql = "select OrderStatus from C_Order where Id=@orderId";
            return sqlManager.ExecuteDataset(CommandType.Text, sql, parms);
        }
        public static bool Api_ServiceOrder(int orderid, int userid)
        {
            var res = true;
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@orderid",orderid),
                new SqlParameter("@userid",userid)
            };
            var sql = "update C_Order set OrderStatus=4 where Id=@orderid and UserId=@userid and OrderStatus=1";
            var ret = sqlManager.ExecuteNonQuery(CommandType.Text, sql, parms);
            if (ret != 1)
                res = false;
            return res;
        }

        public static DataSet Api_GetOrderCountDs(int userid)
        {
            var sqlManager = new SqlManager();
            SqlParameter[] parms =
            {
                new SqlParameter("@userid",userid)
            };
            var sql = "select OrderStatus,COUNT(Id) as Num from C_Order where UserId=@userid GROUP BY OrderStatus";
            return sqlManager.ExecuteDataset(CommandType.Text, sql, parms);
        }
        
        #endregion
    }
}
